using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Win32;
using System.Windows.Forms;

namespace ArchSoft
{
    public class SynchronizeLayer
    {
        string _sourcePath;
        string TempF;
        public SynchronizeLayer(string source, string TempF_)
        {
            _sourcePath = source;
            TempF = TempF_;
        }

        public bool DeleteTarget()
        {
            // Delete .bak file
            try
            {
                DirectoryInfo source = new DirectoryInfo(_sourcePath);
                foreach (DirectoryInfo subDir in source.GetDirectories())
                {
                    foreach (FileInfo file in subDir.GetFiles())
                    {
                        if (!file.Extension.Equals(".dwg") && !file.Extension.Equals(".dwt"))
                        {
                            file.Delete();
                        }
                    }
                }
                return true;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; }
        }

        private void DeleteTempFile()
        {
            DirectoryInfo issueWindow = new DirectoryInfo(_sourcePath);
            foreach (FileInfo adrawing in issueWindow.GetFiles())
                adrawing.Delete();

            foreach (DirectoryInfo dir in issueWindow.GetDirectories())
                if (dir.Name.ToLower().Contains("reference"))
                    dir.Delete(true);
                else
                {
                    foreach (FileInfo adrawing in dir.GetFiles())
                        if (!adrawing.Extension.Contains("dwg") && !adrawing.Extension.Contains("dwt"))
                            adrawing.Delete();
                }
        }


        public string GenerateScriptFile(string ChildWindow)
        {
            string tmp=Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Trang\\Architecture" + "\\LrDefStore.LDI";
            if (!File.Exists(tmp))
            {
                MessageBox.Show("Layer managerment file was not found.", "Missing file");
                return "";
            }
            // Collect drawings
            List<string> issuedDrawings = new List<string>();

            DirectoryInfo issueWindow = new DirectoryInfo(_sourcePath);
            foreach (DirectoryInfo dir in issueWindow.GetDirectories())
            {
                if (dir.Name == "Xref")
                    continue;
                if ((ChildWindow != "") & (dir.Name != ChildWindow))
                    continue;
                foreach (FileInfo adrawing in dir.GetFiles())
                    issuedDrawings.Add(adrawing.FullName);
            }
            // Generate script

            string tempFileName = _sourcePath + @"\" + Guid.NewGuid().ToString() + ".scr";

            FileStream scriptFile = File.Open(tempFileName, FileMode.CreateNew);
            StreamWriter wr = new StreamWriter(scriptFile);

            wr.WriteLine("filedia 0");


            for (int i = 0; i < issuedDrawings.Count - 1; i++)
            {
                ScriptForDetachTitle(wr, false, issuedDrawings[i]);
            }
            ScriptForDetachTitle(wr, true, issuedDrawings[issuedDrawings.Count - 1]);

            wr.WriteLine("filedia 1");
            wr.WriteLine("quit");
            wr.Flush();
            wr.Dispose();

            scriptFile.Close();
            scriptFile.Dispose();
            return tempFileName;
        }

        public string GenerateScriptFile(string childWindow, List<string> drawings)
        {
            if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Trang\\Architecture" + "\\LrDefStore.LDI"))
            {
                MessageBox.Show("Layer managerment file was not found.", "Missing file");
                return "";
            }
            string sourceWindow = _sourcePath + Path.DirectorySeparatorChar + childWindow;
            // Generate script

            string tempFileName = _sourcePath + @"\" + Guid.NewGuid().ToString() + ".scr";

            FileStream scriptFile = File.Open(tempFileName, FileMode.CreateNew);
            StreamWriter wr = new StreamWriter(scriptFile);

            wr.WriteLine("filedia 0");


            for (int i = 0; i < drawings.Count - 1; i++)
            {
                ScriptForDetachTitle(wr, false, sourceWindow + "\\" + drawings[i]);
            }
            ScriptForDetachTitle(wr, true, sourceWindow + "\\" + drawings[drawings.Count - 1]);

            //for (int i = 0; i < issuedDrawings.Count - 1; i++)
            //{
            //    ScriptForDetachTitle(wr, false, issuedDrawings[i]);
            //}
            //ScriptForDetachTitle(wr, true, issuedDrawings[issuedDrawings.Count - 1]);

            wr.WriteLine("filedia 1");
            wr.WriteLine("quit");
            wr.Flush();
            wr.Dispose();

            scriptFile.Close();
            scriptFile.Dispose();
            return tempFileName;
        }

        public string RunSciptFile(string filePath)
        {
            AutocadHelper helper = AutocadHelper.Instance;
            return helper.RunAutoCadScript(filePath, true);
        }

        public string Process(string childWindow, List<string> drawings)
        {          
            string str = "";

            bool tpd = DeleteTarget(); if (!tpd) { return ""; }

            string scriptFile;
            if (drawings == null)
                scriptFile = GenerateScriptFile(childWindow);
            else
                scriptFile = GenerateScriptFile(childWindow, drawings);
            if (scriptFile != "")
                str = RunSciptFile(scriptFile);
            DeleteTempFile();
            return str;
        }

        public string Process(string childWindow)
        {
            return Process(childWindow, null);
        }

        public string Process()
        {
            return Process(string.Empty, null);
        }

        public void ScriptForDetachTitle(StreamWriter wr, bool lastDrawing, string fileName)
        {
            string cx = "";
            int t = 0;
            StreamReader sr;
            try
            {
                sr = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Trang\\Architecture" + "\\LrDefStore.LDI");
                cx = EncodeDecode.GetDecoded(sr.ReadLine()).TrimEnd(new char[] { '\0' });
                t = int.Parse(cx);
            }
            catch
            {
                wr.WriteLine("open \"" + fileName + "\"");
                goto End;
            }
                string Name = "";

                wr.WriteLine("open \"" + fileName + "\"");
                //Set LineType
                wr.WriteLine("TILEMODE");
                wr.WriteLine("1");
                wr.WriteLine("-INSERT");
                wr.WriteLine("\"" + TempF + "\"");//Linetype Drawing
                wr.WriteLine("0,0");
                wr.WriteLine("1");//Drawing Scale
                wr.WriteLine("1");//Drawing Scale
                wr.WriteLine("0");
                wr.WriteLine("ERASE");
                wr.WriteLine("LAST");
                wr.WriteLine("");

                //Create Layer!
                for (int i = 0; i < t; i++)
                {
                    wr.WriteLine("-LAYER");
                    wr.WriteLine("N");//Name
                    Name = EncodeDecode.GetDecoded(sr.ReadLine()).TrimEnd(new char[] { '\0' });
                    wr.WriteLine("\"" + Name + "\"");
                    wr.WriteLine("C");//Color
                    sr.ReadLine();
                    cx = EncodeDecode.GetDecoded(sr.ReadLine()).TrimEnd(new char[] { '\0' });
                    wr.WriteLine(cx);
                    wr.WriteLine("\"" + Name + "\"");
                    sr.ReadLine();
                    cx = EncodeDecode.GetDecoded(sr.ReadLine()).TrimEnd(new char[] { '\0' });
                    wr.WriteLine("Ltype");//Linetype
                    wr.WriteLine("\"" + cx.Split(':')[1].Trim() + "\"");
                    wr.WriteLine("\"" + Name + "\"");
                    wr.WriteLine("");
                }
                sr.Close();
                //12
                //F2
                //Blue
                //5
                //0,0,255
                //Type: Trang Center
                //Hung
                //Red
                //1
                //255,0,0
                //Type: Continuous               
                //wr.WriteLine("-LAYER");
                //wr.WriteLine("N");//Name            
                //wr.WriteLine("Aaa");
                //wr.WriteLine("C");//Color
                //wr.WriteLine("1");
                //wr.WriteLine("Aaa");

                //wr.WriteLine("Ltype");//Linetype
                //wr.WriteLine("Continuous");
                //wr.WriteLine("Aaa");
                //wr.WriteLine("");   

            End:
                wr.WriteLine("QSAVE");
                if (!lastDrawing)
                {
                    wr.WriteLine("Close");
                }                      
        }
    }
}
